package com.example.demo.controller;

import com.example.demo.dao.Alink;
import com.example.demo.service.BookListService;
import com.example.demo.util.HtmlUtil;
import com.example.demo.util.HttpUtilOpti;

import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;

@Controller
@EnableAutoConfiguration
public class BookController extends BookLogger {

    @Autowired
    private BookListService bookListService;

    public String DETAIL = "/detail?address=";

    @RequestMapping("/book/list")
    public String getBookList(String address, String listLabel, Model model) throws Exception {
        // 获取内容并自动编码为字符串
        String content = HttpUtilOpti.get(address);

        HashMap map = bookListService.getListPage(address, content, listLabel);
        model.addAttribute("bookList", map.get("bookList"));
        model.addAttribute("bookInfo", map.get("bookInfo"));
        model.addAttribute("bookTitle", map.get("bookTitle"));
        return "/list";
    }

    // @RequestMapping("/book/download")
    public void downloadBook(String address, String listLabel, Model model) throws Exception {
        // 获取内容并自动编码为字符串
        String content = HttpUtilOpti.get(address);

        HashMap map = bookListService.getListPage(address, content, listLabel);
        // 获取到map中的链接集合
        List<Alink> list = (List<Alink>) map.get("bookList");
        // 遍历链接集合
        for (Alink alink : list) {
            // 获取到章节链接
            String chapterLink = alink.getLink();
            // 获取到章节名称
            String title = alink.getText();
            // 获取章节内容并自动编码为字符串
            String chapterContent = HttpUtilOpti.get(chapterLink);

            // 直接使用自动识别编码后的内容
            String chapterText = HtmlUtil.getHtmlContentByTag(chapterContent, ".container .con");
            // 可根据需要保存或处理 chapterText
        }
    }

    @GetMapping("/")
    public String index() throws Exception {
        return "/index";
    }

}
